package com.zw.demo01.service.impl;

import com.zw.demo01.service.MyAccessService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * @ClassName: MyAccessServiceImpl
 * @Description TODO
 * @Author: zzw
 * @Date: 2023/4/3 22:57
 * @Version 1.0.0
 */
@Service
public class MyAccessServiceImpl implements MyAccessService {


    @Override
    public boolean hasPermission(HttpServletRequest request,Authentication authentication) {
//        获取主体
        Object principal = authentication.getPrincipal();
        System.out.println(principal.toString());
//        判断主体是否存在UserDetails
        if(principal instanceof UserDetails){
//            获取权限
            UserDetails principal1 = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = principal1.getAuthorities();
//            判断请求的uri是否在权限中
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }

        return false;
    }
}
